//订单确认页面
var basePage = require('../../common/BasePage');
var util = require('../../utils/util');
Page({
    behaviors: [basePage],
    data: {
        checkMobile: true,
        /**要访问的仓库 */
        wh_id: 1,
        /**当前选中的仓库信息 */
        warehouse: {},
        /**支付凭证 */
        pay_cert: {
            /**完整图片路径 */
            url: '/assets/photo.png',
            /**后台地址 */
            photo: '',
            /**''未选择;loading 上传中;error 上传失败;ok 上传成功 */
            state: '',
        },
        /**密码设置弹窗 */
        editPassPop: false,
        /**重新设置的密码 */
        repass: '',
        /**支付参数 */
        payData: {},
        /**支付密码 */
        password: '',
        /**是否显示密码输入框 */
        passPop: false,
        /**支付方式 */
        pay: 'coin',
        payType:1,//1微信，2通联
        /**订单信息 */
        order: {},
        /**地址信息 */
        m_addr: null,
        /**选中的优惠券信息 */
        coupon: {
            cid: 0
        },
        show: false,

        price: 0,
        /**设置提交按钮状态 */
        loading: false,
        coupon_radio: '', //优惠券选中项
        /**是否可以提交 */
        can_submit: true,
        activeCar: "", //订单类型
        wuliu: [],
        selectIndex: 0,
        selectList: [],
        city1: "",
        city2: "",
        city3: "",
        company: "",
        phone: "",
        remarks: "",
        specialList: [], //特殊需求
        pack_list: [], //包装

        total_price: 0, //商品价格
        payPrice: 0, //支付价格
        packingFee: 0, //预收运费、包装费
        freightFee: 0, //运费
        CompanyIndex: -1,//选择物流公司
        shippingIndex: 0,
        groupInfo: {},
        buyType: 0, //0购物车1立即购买2预售订单
        showPay: false,
        peisongRadio: "2",
        orderWarehouse: null, //自提地址
        selectArticle: false,
        imgContent: "",
        imgList: [],
        timeInfo: {}, //系统配置
        companyStaffArr:[],//物流人员
        showCompany:false,


    },
    onLoad: function (option) {
        // console.log(option.query);
        let that = this;
        const eventChannel = this.getOpenerEventChannel();
        eventChannel.on('orderData', function (data) {
            console.log("orderData", data);

            that.data.warehouse =data.orderWarehouse|| data.warehouse || getApp().globalData.warehouse;

            /**产品总价 */
            let pdc_amount = 0;
            //     data.data.products.map(function (val) {
            //         val.thumb = that.get_thumb(val.product_img);
            //         pdc_amount += val.product_price * val.product_number;

            //     })
            data.data.pdc_amount = pdc_amount;
            if (data.data.coupon_list && data.data.coupon_list.length) {
                // that.data.coupon = data.data.coupon_list[0]
            }
            var wuliu = data.wuliu ? data.wuliu : []
            var groupInfo = {}
            if (wuliu.length > 0) {
                // groupInfo = wuliu[0].shipping_list[0].group_list[0]
            }

            var order = data.data
            if(data.activeCar != "pindan"){
                if (data.order_pei_type == 1) {
                    order.peiAmount = Number(order.pei_amount).toFixed(2)
                } else if (data.order_pei_type == 2) {
                    order.peiAmount = (Number(order.pei_amount) + Number(data.pei_fast_amount)).toFixed(2)
                }
            }
            

            // console.log(" that.data.coupon", that.data.coupon);
            that.setData({
                wh_id: data.wh_id,
                m_addr: data.m_addr,
                order: order,
                // coupon: that.data.coupon,
                activeCar: data.activeCar,
                wuliu: wuliu,
                specialList: data.specialList,
                // pack_list:data.pack_list,
                groupInfo: groupInfo,
                buyType: data.buyType,
                orderWarehouse:data.orderWarehouse || null,
                peisongRadio: data.order_pei_type ? (data.order_pei_type).toString() : "1"
            })
            
            that.getImage()
            
            if(data.activeCar=='pindan'){
                that.getPayType(1)//获取仓库支付方式
            }else{
                that.getPayType(data.wh_id)//获取仓库支付方式
            }
            if(data.wh_id!=1&&data.wh_id!=4){
                //分仓&&(data.activeCar=='flower'||data.activeCar=='seckill'||data.activeCar=='live_stream')
                that.getTime()
                // that.getCompanyStaff()
            }else{
                that.calculation()
            }
            that.getCompanyStaff()
            
        })
    },
    //获取当前仓库的支付方式1微信，2通联
    // getPayType(){
    //     this.request({
    //         url: this.data.host + '/home/index/warehouse/info',
    //         data: {
    //             wh_id: this.data.wh_id,
    //         }
    //     }, res => {
    //         var data=res.data
    //         var pay="allin"
    //         if (data.pay_type ==1) {
    //             pay='wxpay'
    //         } else {
    //             pay='allin'
    //         }
    //         this.setData({
    //             pay:pay,
    //             payType:data.pay_type
    //         })

    //     });
    // },
    //获取物流人员
    getCompanyStaff(){
        this.request({
            url: this.data.host + '/home/index/companyStaff',
            data: {
                city_code: this.data.m_addr.city_code,
            }
        }, res => {
            this.setData({
                companyStaffArr:res.data
            })

        });
    },
    onConfirm(e){
        console.log(e)
        this.setData({
            company:e.detail.value.name,
            phone:e.detail.value.phone,
            showCompany:false
        })
    },
    stop(){},
    onShowcompany(){
        this.setData({
            showCompany:true
        })
    },
    onClose2(){
        this.setData({
            showCompany:false
        })
    },
    //查询系统配置
    getTime() {
        this.request({
            url: this.data.host + '/home/index/config',
            data: {
                wh_id: this.data.wh_id,
                type: 2
            }
        }, res => {
            var timeInfo = res.data
            var deliveryType = []
            var peisongRadio = this.data.peisongRadio

            var myDate = new Date(); //实例一个时间对象； 
            var y = myDate.getFullYear(); //获取系统的年； 
            var m = myDate.getMonth() + 1; //获取系统月份，由于月份是从0开始计算，所以要加1 
            var d = myDate.getDate(); // 获取系统日， 
            var time = new Date().getTime()

            if (timeInfo.general_pei == 1) {

                var fs = y + "-" + m + "-" + d + " " + timeInfo.general_stime
                fs = new Date(fs).getTime()
                var fl = y + "-" + m + "-" + d + " " + timeInfo.general_ltime
                fl = new Date(fl).getTime()
                if (fs > time || fl < time) {
                    //不可自提
                    deliveryType.push({
                        name: "普通配送",
                        state: '1',
                        select: false
                    })
                } else {
                    deliveryType.push({
                        name: "普通配送",
                        state: '1',
                        select: true
                    })
                }
            }
            if (timeInfo.self_pei == 1) {
                var fs = y + "-" + m + "-" + d + " " + timeInfo.self_stime
                console.log("fs",fs)
                fs = new Date(fs).getTime()
                var fl = y + "-" + m + "-" + d + " " + timeInfo.self_ltime
                fl = new Date(fl).getTime()
                if (fs > time || fl < time) {
                    //不可自提
                    deliveryType.push({
                        name: "自提",
                        state: '0',
                        select: false
                    })
                } else {
                    deliveryType.push({
                        name: "自提",
                        state: '0',
                        select: true
                    })
                }

            }
            if (timeInfo.fast_pei == 1) {

                var fs = y + "-" + m + "-" + d + " " + timeInfo.fast_stime
                fs = new Date(fs).getTime()
                var fl = y + "-" + m + "-" + d + " " + timeInfo.fast_ltime
                fl = new Date(fl).getTime()
                if (fs > time || fl < time) {
                    //不可自提
                    deliveryType.push({
                        name: "加急配送",
                        state: '2',
                        select: false
                    })
                } else {
                    deliveryType.push({
                        name: "加急配送",
                        state: '2',
                        select: true
                    })
                }
            }
            
            if (timeInfo.express_pei == 1) {

                var fs = y + "-" + m + "-" + d + " " + timeInfo.express_stime
                fs = new Date(fs).getTime()
                var fl = y + "-" + m + "-" + d + " " + timeInfo.express_ltime
                fl = new Date(fl).getTime()
                if (fs > time || fl < time) {
                    //不可自提
                    deliveryType.push({
                        name: "物流发货",
                        state: '3',
                        select: false
                    })
                } else {
                    deliveryType.push({
                        name: "物流发货",
                        state: '3',
                        select: true
                    })
                }
            }
            console.log("deliveryType",deliveryType)
            if (deliveryType.length > 0) {
                for(var i=0;i<deliveryType.length;i++){
                    if(deliveryType[i].select){
                        peisongRadio = deliveryType[i].state
                        break;
                    }
                }
                
            }
            this.setData({
                timeInfo: res.data,
                deliveryType: deliveryType,
                peisongRadio: peisongRadio
            })
            console.log("peisongRadio",peisongRadio)
            this.calculation()

        });
    },
    //分仓获取图片
    getImage() {
        var wh_id = this.data.wh_id
        // var article_id = 0
        // if (wh_id == 2) { //榆林2
        //     article_id = 69
        // } else if (wh_id == 8) { //呼市8
        //     article_id = 68
        // } else if (wh_id == 9) { //包头9
        //     article_id = 67
        // } else if (wh_id == 10) { //鄂尔多斯10
        //     article_id = 70
        // } else if (wh_id == 6) { //宝鸡直营仓6
        //     article_id = 83
        // } else if (wh_id == 3) { //西安3
        //     article_id = 97
        // }else if (wh_id == 5) { //延安5
        //     article_id = 103
        // }else {
        //     return;
        // }
        this.request({
            url: this.data.host + "/home/whDeliveryMsg",
            data: {
                wh_id: this.data.wh_id
            }
        }, res => {
            var imgContent = res.data.article.content
            imgContent = imgContent.replace(/<img [^>]*src=['"]/g, `<img src="${this.data.imgHost}/`)
                .replace(/<img/gi, '<img class="fwb-img"')
                .replace(/<section/g, '<div')
                .replace(/\/section>/g, '\div>')
            var imgs = [];
            if (imgContent.indexOf("src") >= 0) {
                //正则匹配所有图片路径
                var info = ""
                info = imgContent.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
                    imgs.push(capture);
                    return '';
                });
                // console.log("imgs",imgs)
            }
            // console.log("imgContent", imgContent.replace(/<img/gi))
            this.setData({
                imgContent: imgContent,
                imgList: imgs
            })
        })
    },

    onArticle() {
        this.setData({
            selectArticle: !this.data.selectArticle
        })
    },

    calculation() {
        var payPrice = 0; //支付金额
        var freight = 0 //运费
        var packingFee = 0; //打包费+运费
        var wh_id = this.data.wh_id

        if (this.data.wuliu.length > 0) {
            if (wh_id == 1 || wh_id == 4) {
                freight = this.data.groupInfo.freight || 0
                // freight=this.data.wuliu[this.data.selectIndex].shipping_list[this.data.shippingIndex].group_list[this.data.CompanyIndex].freight
                // packingFee=this.data.wuliu[this.data.selectIndex].freight+this.data.order.pack_amount
            } else {
                freight = this.data.order.freight
                // packingFee=this.data.wuliu[this.data.selectIndex].freight+this.data.order.freight+this.data.order.pack_amount
            }
        } else {
            if (wh_id != 1 && wh_id != 4) {
                freight = this.data.order.freight
            }
        }
        // packingFee=freight+this.data.order.pack_amount
        // packingFee=this.data.order.pack_amount
        if (this.data.activeCar == "dounan") {
            freight = 0
            // packingFee=this.data.order.pack_amount
        }
        // console.log("total_price",this.data.order.total_price)
        //支付费用=商品价+运费+打包费-优惠券

        if (wh_id == 1 || wh_id == 4) { //总仓或分仓拼单
            payPrice = Number(this.data.order.total_price) + Number(freight) + Number(this.data.order.pack_amount)
        } else { //分仓
            payPrice = Number(this.data.order.total_price)
        }

        if (this.data.buyType != 2) {
            payPrice = payPrice - Number(this.data.order.total_youhui)
        }
        console.log("peisongRadio2",this.data.peisongRadio)
        //&& (this.data.activeCar == "flower" || this.data.activeCar == "seckill"||this.data.activeCar=='live_stream')
        if (this.data.wh_id != 1 && this.data.wh_id != 4 && (this.data.peisongRadio == 1 || this.data.peisongRadio == 2)&& this.data.activeCar != "pindan"  ) { //配送费
            payPrice = payPrice + Number(this.data.order.peiAmount)
            console.log("计算配送费",payPrice)
        }
        // payPrice=payPrice<0?0:payPrice
        // console.log("payPrice",payPrice)
        this.setData({
            payPrice: payPrice,
            freightFee: freight
            // packingFee:packingFee
        })
    },
    /**
     * 凭证上传
     */
    img_upload(e) {
        let that = this;
        /**上传图片的对象 */
        let img = e.currentTarget.dataset.img;
        wx.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            success(imgRes) {
                // tempFilePath可以作为img标签的src属性显示图片
                const tempFilePaths = imgRes.tempFilePaths;
                // console.log("tempFilePaths", tempFilePaths);
                let photo = {}; //用于更新视图诗句
                let id_photo_front = photo[img] = that.data[img];
                id_photo_front.url = tempFilePaths[0];
                id_photo_front.state = "loading";
                // console.log("photo", photo)
                that.setData(photo)
                wx.uploadFile({
                    filePath: tempFilePaths[0],
                    name: 'image',
                    url: that.data.host + '/home/upload/image',
                    formData: {
                        from: 'verify'
                    },
                    success(res) {
                        id_photo_front.state = "error";
                        // id_photo_front.photo='';
                        // console.log("home/upload/image", res);
                        if (res.statusCode != 200) {
                            return wx.showModal({
                                showCancel: false,
                                content: res.errMsg || '上传失败',
                            })
                        }
                        let resObj = JSON.parse(res.data);
                        if (resObj.code) {
                            return wx.showToast({
                                title: resObj.msg,
                                icon: 'none'
                            })
                        }
                        id_photo_front.state = "ok";
                        id_photo_front.photo = resObj.data.path;

                    },
                    fail() {
                        id_photo_front.state = "error";
                        wx.showModal({
                            showCancel: false,
                            content: '上传接口异常',
                        })
                    },
                    complete() {
                        that.setData(photo)
                    }
                });
            },
            fail(e) {
                wx.showToast({
                    title: e.errMsg || '调用微信文件失败',
                    icon: 'none'
                })
                // console.log(e);
            }
        })
    },
    /**设置支付密码 */
    edit_pass() {
        this.request({
            url: this.data.host + '/home/user/editPasswd',
            data: {
                password: this.data.repass
            },
            method: 'post'
        }, res => {
            wx.showToast({
                title: '设置成功',
                icon: 'none'
            });
            this.setData({
                editPassPop: false
            })
        });
    },
    pay_click(e) {
        if(this.data.CompanyIndex==-1 && this.data.wh_id==1&&this.data.activeCar!='dounan'){
            wx.showToast({
              title: '请选择物流公司',
              icon:"none"
            })
            return;
        }
        if (!this.data.selectArticle) {
            wx.showToast({
                title: '请阅读并同意源花买家协议',
                icon: "none"
            })
            return;
        }
        if((this.data.groupInfo.have_apll==1||(this.data.wh_id!=1&&this.data.wh_id!=4&&this.data.activeCar!='pindan'))&&this.data.activeCar!='dounan'){
            if(this.data.company&&!this.data.phone){
                wx.showToast({
                    title: '请填写物流号码',
                    icon:"none"
                  })
                  return;
            }

            if(this.data.phone&&!this.data.company){
                wx.showToast({
                    title: '请填写物流公司',
                    icon:"none"
                  })
                  return;
            }
        }
        
        if(this.data.activeCar=='next_day'&&this.data.order.express_days!=0){
            wx.showModal({
                title: '提示',
                content: '订单于'+this.data.order.express_days+'日后送达',
                showCancel:true,
                complete: (res) => {
                  
                  if (res.confirm) {
                    this.setData({
                        showPay: true
                    })
                  }
                }
              })
        }else{
            this.setData({
                showPay: true
            })
        }
        

    },
    /**
     * 确认订单（立即支付）
     */
    submit_order() {
        let that = this;
        if (!this.data.can_submit) {
            return wx.showToast({
                title: '请间隔5s后提交',
                icon: 'none'
            })
        }
        this.data.can_submit = false;
        setTimeout(() => {
            this.data.can_submit = true
        }, 5000);

        if (!this.data.m_addr.addr_id && this.data.peisongRadio != 0) {
            wx.showModal({

                cancelText: '取消',

                confirmText: '确认',
                content: "请选择地址",

                showCancel: true,
                title: '提示',
                success: (result) => {

                },

            })
            return;
        }

        if ((this.data.wh_id == 1 || this.data.wh_id == 4) && this.data.activeCar != "dounan" && this.data.wuliu.length <= 0) {
            wx.showModal({

                cancelText: '取消',

                confirmText: '确认',
                content: "该区域不支持下单",

                showCancel: true,
                title: '提示',
                success: (result) => {

                },

            })
            return;
        }


        let tip = '此商品由' + this.data.warehouse.title + "派送，请确认";
        console.log("warehouse",this.data.warehouse)
        if (this.data.warehouse.wh_id == 1) {
            tip = '此商品由' + this.data.warehouse.title + "派送，请确认";
        }
        wx.showModal({

            cancelText: '取消',

            confirmText: '确认',
            content: tip,

            showCancel: true,
            title: '提示',
            success: (result) => {
                if (result.confirm) {
                    this.setData({
                        loading: true,
                        showPay: false
                    })
                    that.req_submit()
                }
            },

        })


    },
    req_submit() {
        // console.log("this.data.activeCar",this.data.activeCar)
        var pei_type = 0
        if ((this.data.wh_id == 1 || this.data.wh_id == 4) && this.data.activeCar != "dounan") {
            pei_type = this.data.groupInfo.shipping_type
            // pei_type=this.data.wuliu[this.data.selectIndex].shipping_list[this.data.shippingIndex].group_list[this.data.CompanyIndex].shipping_type
        }
        var transfer = ""
        if (this.data.city1 && this.data.city2 && this.data.city3) {
            transfer = this.data.city1 + "," + this.data.city2 + "," + this.data.city3
        } else if (this.data.city1 && this.data.city2) {
            transfer = this.data.city1 + "," + this.data.city2
        } else if (this.data.city1) {
            transfer = this.data.city1
        }
        var param = {
            pei_type: pei_type,
            addr_id: this.data.m_addr.addr_id,

            intro: this.data.remarks,
            extra: [],
            transfer: transfer,
            apll_title: this.data.company,
            apll_phone: this.data.phone
        }
        param.intro = util.replaceStr(param.intro)
        for (var i = 0; i < this.data.selectList.length; i++) {
            param.extra.push({
                title: this.data.selectList[i].title,
                content: this.data.selectList[i].content
            })
        }
        //&& (this.data.activeCar == "flower" || this.data.activeCar == "seckill"||this.data.activeCar=='live_stream')
        //分仓提交配送方式
        if (this.data.wh_id != 1 && this.data.wh_id != 4 ) {
            param.order_pei_type = this.data.peisongRadio
        }

        console.log("提交的数据", param)
        if (this.data.payData && this.data.payData.order_id) {
            return this.check_pay(); //已经下单成功，直接进行支付
        }
        var url = "/home/cart/new_handle" //购物车
        if (this.data.buyType == 0) { //购物车
            param.cid = this.data.coupon.cid

            if (this.data.activeCar == "pindan") {
                url = "/home/wh/cart/handle"
            }

        } else if (this.data.buyType == 1) { //如果是立即购买
            console.log("activeCar", this.data.activeCar)
            if (this.data.activeCar == "pindan") {
                url = "/home/wh/order/handle"
            } else {
                url = "/home/flower/handle"
            }

            param.pid = this.data.order.product.pid
            param.cid = this.data.coupon.cid
            param.nums = this.data.order.product.product_number
        } else if (this.data.buyType == 2) { //预售订单
            url = "/home/yuyue/handleNew"
            param.yy_id = this.data.order.yy_id
            param.nums = this.data.order.product_number
        }

        if (this.data.activeCar != "pindan") {
            param.from = this.data.activeCar
        }
        //请求购物车数据
        this.request({
            url: this.data.host + url + '?wh_id=' + this.data.wh_id,
            loadingTip: "正在提交",
            data: param,
            method: 'post'
        }, this.submit_ok, null, res => {
            this.setData({
                loading: false,
                showPay: false
            })
        });
    },
    submit_ok(obj) {
        // console.log("submit_ok", obj);

        this.data.payData = {
            order_id: obj.data.order_id,
            code: this.data.pay
        }
        this.check_pay();
    },
    /**检查支付方式 */
    check_pay() {
        this.pay_order()
    },
    submit_pass() {
        if (!this.data.password) {
            return wx.showToast({
                title: '请先输入密码',
                icon: 'none'
            })
        }
        this.setData({
            passPop: false
        })
        this.data.payData.password = this.data.password;
        this.pay_order()
        // console.log("password",this.data.password);
        // console.log("payData",this.data.payData);
    },
    /**
     * 支付订单
     */
    pay_order() {
        // let that=this;
        this.data.pay_cert.photo ? this.data.payData.pay_cert = this.data.pay_cert.photo : '';
        this.request({
            url: this.data.host + '/home/payment/order',
            loadingTip: "正在提交",
            method: "POST",
            data: this.data.payData
        }, res => {
            //  console.log("payment/order",res,this.data.payData.code);
            if (this.data.payData.code == 'wxpay') { //调用微信支付
                wx.requestPayment({
                    ...res.data.pay_data,
                    success(res) {
                        wx.showToast({
                            title: '支付成功',
                        })

                    },
                    fail(err) {
                        wx.showToast({
                            title: '支付失败',
                            icon: 'none'
                        })
                        console.error('pay fail', err)
                    },
                    complete() {
                        wx.redirectTo({
                            url: '/pages/cls/my_order/order',
                        })
                    }
                })
            } else if (this.data.payData.code == 'allin') {
                //通联支付
                var payInfo = res.data.payInfo
                if (payInfo) {//调起微信支付
                    payInfo = JSON.parse(payInfo)
                    wx.requestPayment({
                        ...payInfo,
                        success(res) {
                            wx.showToast({
                                title: '支付成功',
                            })
    
                        },
                        fail(err) {
                            wx.showToast({
                                title: '支付失败',
                                icon: 'none'
                            })
                            console.error('pay fail', err)
                        },
                        complete() {
                            wx.redirectTo({
                                url: '/pages/cls/my_order/order',
                            })
                        }
                    })
                }else if(res.data.extraData){//跳转收银台小程序
                    var extraData=res.data.extraData

                    this.alinePay(extraData,this.pay_ok)

                }else{
                    wx.showToast({
                      title: '支付失败',
                      icon:"none"
                    })
                    setTimeout(()=>{
                        wx.redirectTo({
                            url: '/pages/cls/my_order/order',
                        })
                    },500)
                }
                
            } else {
                wx.redirectTo({
                    url: '/pages/cls/my_order/order',
                })
            }
            //  return;

        }, null, res => {
            this.setData({
                loading: false,
            })
        });
    },
    //收银台支付回调
    pay_ok(){
        wx.redirectTo({
            url: '/pages/cls/my_order/order',
        })
    },
    addr_click() {
        let that = this;
        wx.navigateTo({
            url: '/pages/addr/AddrList',
            events: {
                change_addr: function (data) {
                    // console.log("change_addr", data);
                    that.setData({
                        m_addr: data.addr,
                        company:"",
                        phone:"",
                    })
                    //查询订单信息
                    that.getOrderInfo()
                    //查询物流人员
                    that.getCompanyStaff()
                }
            }
        })
    },
    getOrderInfo() {
        //默认为购物车（自提配送只做交易大厅）
        var param = {}
        if (this.data.m_addr.addr_id) {
            param = {
                addr_id: this.data.m_addr.addr_id
            }
        }
        var url = '/home/cart/new_cart?wh_id=' + this.data.wh_id + "&from=" + this.data.activeCar
        if (this.data.buyType == 2) { //预售订单
            url = '/home/yuyue/preinfoNew?yy_id=' + this.data.order.yy_id + "&nums=" + this.data.order.product_number+"&order_pei_type="+this.data.peisongRadio
        }


        if (this.data.buyType == 0) { //购物车
            if (this.data.activeCar == "pindan") {
                url = "/home/wh/cart/cart?wh_id=" + this.data.wh_id
            }else if ( this.data.wh_id != 1 && this.data.wh_id != 4) {
            //如果是交易大厅且是分仓，传配送方式(this.data.activeCar == "flower" || this.data.activeCar == "seckill"||this.data.activeCar=='live_stream') &&
                url = '/home/cart/new_cart?wh_id=' + this.data.wh_id + "&from=" + this.data.activeCar + "&order_pei_type=" + this.data.peisongRadio
            }
        } else if (this.data.buyType == 1) { //立即购买
            if (this.data.activeCar == "pindan") {
                url = "/home/wh/order/preInfo?wh_id=" + this.data.wh_id + "&pid=" + this.data.order.product.pid + "&nums=" + this.data.order.nums
            } //如果是交易大厅且是分仓，传配送方式(this.data.activeCar == "flower" || this.data.activeCar == "seckill"||this.data.activeCar=='live_stream') &&
            else if ( this.data.wh_id != 1 && this.data.wh_id != 4) {
                url = "/home/flower/preInfo?wh_id=" + this.data.wh_id + "&from=" + this.data.activeCar + "&pid=" + this.data.order.product.pid + "&nums=" + this.data.order.nums + "&order_pei_type=" + this.data.peisongRadio
            } else {
                url = "/home/flower/preInfo?wh_id=" + this.data.wh_id + "&from=" + this.data.activeCar + "&pid=" + this.data.order.product.pid + "&nums=" + this.data.order.nums
            }
        }
        this.request({
            url: this.data.host + url,
            data: param
        }, res => {
            let pdc_amount = 0;
            var that = this
            res.data.pdc_amount = pdc_amount;
            if (res.data.coupon_list && res.data.coupon_list.length) {
                // that.data.coupon = res.data.coupon_list[0]
            }

            var wuliu = res.data.freight_list ? res.data.freight_list : []
            var groupInfo = {}
            if (wuliu.length > 0) {
                groupInfo = wuliu[0].shipping_list[0].group_list[0]
            }

            var order = res.data
            if(this.data.activeCar != "pindan"){
                if (res.order_pei_type == 1) {
                    order.peiAmount = Number(order.pei_amount).toFixed(2)
                } else if (res.order_pei_type == 2) {
                    order.peiAmount = (Number(order.pei_amount) + Number(order.pei_fast_amount)).toFixed(2)
                }
            }
            
            // console.log(" that.data.coupon", that.data.coupon);
            that.setData({
                order: order,
                // coupon: that.data.coupon,
                // activeCar:data.activeCar,
                wuliu: wuliu,
                specialList: res.data.extra_list,
                selectList: [],
                // pack_list:res.data.pack_list,
                groupInfo: groupInfo,
                selectIndex: 0,
                CompanyIndex: -1,
                shippingIndex: 0,
                orderWarehouse: res.warehouse //自提仓库地址
            })


        }, null, (res) => {
            this.calculation()
        });
    },
    open_van_action_sheet() {
        this.setData({
            show: true
        });
    },
    onClose() {
        this.setData({
            show: false,
            showPay: false
        });
    },
    onSelect(event) {
        // console.log(event.detail);
    },
    onClick(event) {
        let name = event.currentTarget.dataset.name;
        this.data.payData.code = name;
        this.setData({
            pay: name,
        })
    },
    clickUpload() {
        // if (parseInt(this.data.radio) !== 3) {
        //     wx.showToast({
        //         title: '仅线下支付允许上传凭证',
        //         icon: 'none'
        //     })
        // }
    },
    radioChange(e) {
        // console.log("radioChange", e)
        this.setData({
            coupon_radio: e.detail,
            show: false
        })
    },
    //选择优惠券
    coupon_click(e) {
        // console.log("coupon", e.currentTarget.dataset.coupon);
        let coupon = e.currentTarget.dataset.coupon;
        // console.log("order", this.data.order);
        let order = this.data.order;
        order.total_youhui = coupon.coupon_amount;
        order.amount = order.total_price - coupon.coupon_amount;
        //amount=total_price-total_youhui
        // order.total_youhui=coupon.coupon_amount;
        this.setData({
            coupon,
            order,
            show: false
        })
        this.calculation()
    },
    /**显示密码重置弹窗 */
    show_edit() {
        this.setData({
            editPassPop: true
        })
    },


    /* 选择物流 */
    clickwuliu(e) {
        var groupInfo = {}
        // var groupInfo = this.data.wuliu[e.currentTarget.dataset.index].shipping_list[0].group_list[0]
        this.setData({
            selectIndex: e.currentTarget.dataset.index,
            CompanyIndex: -1,
            shippingIndex: 0,
            groupInfo: groupInfo
        })
        this.calculation()
    },
    clickshipping(e) {
        console.log(e)
        var groupInfo = this.data.wuliu[this.data.selectIndex].shipping_list[e.currentTarget.dataset.key].group_list[e.currentTarget.dataset.index]
        if(groupInfo.is_stop==1){
            wx.showModal({
              title: '当前物流公司已停用',
              content: groupInfo.stop_cause,
              showCancel:false,
              complete: (res) => {
                
              }
            })
            return;
        }
        this.setData({
            CompanyIndex: e.currentTarget.dataset.index,
            shippingIndex: e.currentTarget.dataset.key,
            groupInfo: groupInfo
        })
        this.calculation()
    },
    toShipping() {
        var that = this
        if(this.data.CompanyIndex==-1){
            wx.showToast({
              title: '请选择物流公司',
              icon:"none"
            })
            return;
        }
        wx.navigateTo({
            url: '/pages/logistics/shipping/shipping?selectIndex=' + this.data.selectIndex + "&CompanyIndex=" + this.data.CompanyIndex + "&shippingIndex=" + this.data.shippingIndex,
            success: function (obj) {
                // 通过eventChannel向被打开页面传送数据

                obj.eventChannel.emit('wuliu', {
                    wuliu: that.data.wuliu,
                    // pack_list:that.data.pack_list
                })
            },
            events: {
                change_selectIndex: function (data) {
                    // console.log("change_selectIndex%%%%", data);
                    var groupInfo = that.data.wuliu[data.selectIndex].shipping_list[data.shippingIndex].group_list[data.CompanyIndex]
                    that.setData({
                        selectIndex: data.selectIndex,
                        CompanyIndex: data.CompanyIndex,
                        shippingIndex: data.shippingIndex,
                        groupInfo: groupInfo
                    })
                    that.calculation();
                }
            }

        })
    },
    toSpecial() {
        var that = this
        wx.navigateTo({
            url: '/pages/logistics/special/special',
            success: function (obj) {
                // 通过eventChannel向被打开页面传送数据

                obj.eventChannel.emit('specialList', {

                    specialList: that.data.specialList
                })
            },
            events: {
                change_special: function (data) {
                    // console.log("change_special%%%%", data);
                    that.setData({
                        selectList: data.selectList,
                        specialList: data.specialList
                    })
                }
            }

        })
    },
    onChange(e) {
        // console.log(e)
        var key = e.currentTarget.dataset.key
        this.data[key] = e.detail
    },
    //选择配送方式
    onChangepeisong(e) {
        var timeInfo = this.data.timeInfo

        var myDate = new Date(); //实例一个时间对象； 
        var y = myDate.getFullYear(); //获取系统的年； 
        var m = myDate.getMonth() + 1; //获取系统月份，由于月份是从0开始计算，所以要加1 
        var d = myDate.getDate(); // 获取系统日， 
        var time = new Date().getTime()

        if (e.detail == 0) {
            //自提
            var fs = y + "-" + m + "-" + d + " " + timeInfo.self_stime
            console.log("fs",fs)
            fs = new Date(fs).getTime()
            var fl = y + "-" + m + "-" + d + " " + timeInfo.self_ltime
            fl = new Date(fl).getTime()
            console.log("fs",new Date(fs))
                console.log("fs",new Date(fs).getTime())
            if (fs > time || fl < time) {
                wx.showToast({
                    title: '当前时间不可选择自提',
                    icon: "none"
                })
                return;
            }
        } else if (e.detail == 1) {
            //普通配送
            var fs = y + "-" + m + "-" + d + " " + timeInfo.general_stime
            fs = new Date(fs).getTime()
            var fl = y + "-" + m + "-" + d + " " + timeInfo.general_ltime
            fl = new Date(fl).getTime()

            if (fs > time || fl < time) {
                wx.showToast({
                    title: '当前时间不可选择普通配送',
                    icon: "none"
                })
                return;
            }
        } else if (e.detail == 2) {
            //加急配送
            var fs = y + "-" + m + "-" + d + " " + timeInfo.fast_stime
            fs = new Date(fs).getTime()
            var fl = y + "-" + m + "-" + d + " " + timeInfo.fast_ltime
            fl = new Date(fl).getTime()

            if (fs > time || fl < time) {
                wx.showToast({
                    title: '当前时间不可选择加急配送',
                    icon: "none"
                })
                return;
            }
        } else if (e.detail == 3) {
            //物流发货
            var fs = y + "-" + m + "-" + d + " " + timeInfo.express_stime
            fs = new Date(fs).getTime()
            var fl = y + "-" + m + "-" + d + " " + timeInfo.express_ltime
            fl = new Date(fl).getTime()

            if (fs > time || fl < time) {
                wx.showToast({
                    title: '当前时间不可选择物流发货',
                    icon: "none"
                })
                return;
            }
        }
        this.setData({
            peisongRadio: e.detail
        })
        this.getOrderInfo()
    },
    //放大图片
    onImg(e) {
        // var img = e.currentTarget.dataset.img
        // var list = []
        // list.push(img)
        var list = this.data.imgList
        wx.previewImage({
            current: '', // 当前显示图片的 http 链接
            urls: list // 需要预览的图片 http 链接列表
        })
    },
    //跳转源花买家协议
    toArticle() {
        var wh_id = this.data.wh_id
        var article_id = 52
        if (wh_id == 1) { //昆明
            article_id = 52
        } else if (wh_id == 9) { //包头
            article_id = 53
        } else if (wh_id == 5) { //延安
            article_id = 57
        } else if (wh_id == 7) { //宝鸡7
            article_id = 56
        } else if (wh_id == 2) { //榆林
            article_id = 54
        } else if (wh_id == 8) { //呼市
            article_id = 55
        } else if (wh_id == 10) { //鄂尔多斯仓
            article_id = 74
        } else if (wh_id == 6) { //宝鸡直营仓6
            article_id = 84
        }else if (wh_id ==3) { //西安3
            article_id = 105
        }
        wx.navigateTo({
            url: '/pages/article/Index?article_id=' + article_id,
        })
    }
})